package com.uduew.sjd.ui.mine

import android.os.Bundle
import android.view.View
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.uduew.sjd.BR
import com.uduew.sjd.R
import com.uduew.sjd.api.AllLoanOrdersApi
import com.uduew.sjd.message.Messages
import com.uduew.sjd.message.PageMessenger
import com.uduew.sjd.net.DataResult
import com.uduew.sjd.request.AllLoanOrdersRequester
import com.uduew.sjd.ui.adapter.LoanOrderAdapter
import com.uduew.sjd.ui.base.BaseFragment
import com.uduew.sjd.ui.base.StateHolder
import com.uduew.sjd.utils.ToastUtils
import com.uduew.sjd.utils.Utils
import com.google.android.material.tabs.TabLayout
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.kunminx.architecture.ui.state.State
import com.uduew.sjd.view.EmptyView

class AllLoanOrdersFragment : BaseFragment() {
    lateinit var mState: AllLoanOrdersStates
    private lateinit var allLoanOrdersRequester: AllLoanOrdersRequester
    private lateinit var mAdapter: LoanOrderAdapter
    private lateinit var mMessenger: PageMessenger

    override fun initViewModel() {
        mState = getFragmentScopeViewModel(AllLoanOrdersStates::class.java)
        allLoanOrdersRequester = getActivityScopeViewModel(AllLoanOrdersRequester::class.java)
        mMessenger = getApplicationScopeViewModel(PageMessenger::class.java)
    }

    override fun getDataBindingConfig(): DataBindingConfig? {
        mAdapter = LoanOrderAdapter(requireContext())
        mAdapter.setOnDetailClickListener { item, position ->
            val bundle = Bundle()
            bundle.putParcelable("orderDetail", item)
            nav().navigate(R.id.action_navigation_order_to_loan_detail_fragment, bundle)
        }
        return DataBindingConfig(R.layout.fragment_allloanorders, BR.vm, mState)
            .addBindingParam(BR.adapter, mAdapter)
            .addBindingParam(BR.listenerTab, TabListenerHandler())
            .addBindingParam(BR.click, Click())
            .addBindingParam(BR.titleBarListener, TitleBarListener())
            .addBindingParam(BR.emptyListener, EmptyListener())
            .addBindingParam(BR.refreshListener, ListenerRefreshHandler())
    }

    inner class ListenerRefreshHandler : OnRefreshListener {
        override fun onRefresh() {
            requestData(mState.debrief)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mMessenger.output(this) { messages ->
            if (messages.eventId == Messages.EVENT_SELECT_BACK) {
                nav().popBackStack()
                mMessenger.input(Messages(Messages.EVENT_SELECT_HOME))
            }
        }
        allLoanOrdersRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<AllLoanOrdersApi.ResAllLoanOrdersBean> ->
            mState.refreshState.set(false)
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.let {
                mState.list.set(it.mamaguy.thorough)
                if (mState.list.get()?.size == 0) {
                    mState.emptyState.set(true)
                } else {
                    mState.emptyState.set(false)
                }
            }
        }
        val type: Int? = arguments?.getInt("type")

        type.let {
            if (type != null) {
                if (type == 1) {
                    val debrief = ArrayList<String>()
                    debrief.add("underwent") //待还
                    this.requestData(debrief)//审批中
                } else if (type == 2) {
                    val debrief = ArrayList<String>()
                    debrief.add("firemen") //待还
                    this.requestData(debrief)//待还款
                } else if (type == 8) {
                    val debrief = ArrayList<String>()
                    debrief.add("missive") //待还
                    requestData(debrief)
                } else {
                    val debrief = ArrayList<String>()
                    requestData(debrief)
                }
                mState.defSelect.set(type)
            } else {
                val debrief = ArrayList<String>()
                requestData(debrief)
            }

        }

    }

    fun requestData(type: ArrayList<String>) {
        WaitDialog.show(getString(R.string.loading))

        mState.debrief = type
        allLoanOrdersRequester.request(
            this@AllLoanOrdersFragment,
            "",
            type,
            mState.coimbatore.get(),
            mState.piat.get()
        )
    }
//    "phylogenic": "enum //订单状态，返回所有订单为null或者不传，支持的状态值：underwent-审批中、monica-审核通过、culminate-拒绝、firemen-放款成功/还款中、pathetical-打款失败、breeks-逾期、missive-结清",

    inner class TabListenerHandler : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab?) {
            val statusMap = mapOf(
                0 to emptyList<String>(),
                1 to listOf("underwent"),
                2 to listOf("firemen","breeks"),
                3 to listOf("culminate"),
                4 to listOf("monica"),
                5 to listOf("firemen"),
                6 to listOf("pathetical"),
                7 to listOf("breeks"),
                8 to listOf("missive")
            )
            tab?.position?.let { position ->
                statusMap[position]?.let { params ->
                    this@AllLoanOrdersFragment.requestData(ArrayList(params))
                }
            }
        }


        override fun onTabUnselected(tab: TabLayout.Tab?) {
        }

        override fun onTabReselected(tab: TabLayout.Tab?) {
        }
    }

    inner class Click {
    }

    inner class TitleBarListener : OnTitleBarListener {
        override fun onLeftClick(titleBar: TitleBar?) {
            super.onLeftClick(titleBar)
            nav().popBackStack()
        }

        override fun onRightClick(titleBar: TitleBar?) {
            super.onRightClick(titleBar)
        }
    }


    inner class EmptyListener : EmptyView.OnEmptyListener {

        override fun onRetry() {

        }

        override fun onClick() {
            if (!Utils.checkDebounce()) return
            nav().popBackStack()
            mMessenger.input(Messages(Messages.EVENT_SELECT_HOME))
        }

    }

    class AllLoanOrdersStates : StateHolder() {

        val emptyState: State<Boolean> = State(false)
        val phylogenic: State<String> = State("")
        var arrayList: ArrayList<String> = ArrayList()
        var debrief: ArrayList<String> = arrayList
        val coimbatore: State<Int> = State(1)
        val piat: State<Int> = State(10)
        val refreshState: State<Boolean> = State(true)
        val defSelect: State<Int> = State(0)

        //获取一个月之前的时间戳
        val polyphyleticism: State<String> = State(Utils.getOneMonthAgoTimestamp().toString())
        val nepotistical: State<String> = State(System.currentTimeMillis().toString())
        val list: State<ArrayList<AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean>> =
            State<ArrayList<AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean>>(
                ArrayList<AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean>()
            )
    }
}